<?php

class Service_keywords extends MY_Service
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('Model_common');
        $this->load->model('Model_keywords');
        $this->load->library('EmojiUtil');
    }

    public function getList($page = 1, $cond = [], $size = 40, $order = 'ASC')
    {
        $where = "";
        foreach ($cond as $key => $val) {
            if ($key == 'keyword') {
                $where .= " AND `$key` like '%$val%' ";
            } else {
                $where .= " AND `$key` = '$val' ";
            }
        }
        $limit_start = ($page - 1) * $size;
        $sql = "SELECT keywords.id, keywords.keyword, keywords.num, keywords.keyword tag FROM url_keywords INNER JOIN keywords ON url_keywords.key_id = keywords.id WHERE 1=1 $where GROUP BY url_keywords.key_id ORDER BY num $order limit ?, ?";
        $result = $this->Model_common->query($sql, [$limit_start, $size]);
        return $result;
    }

    public function getListByKeyword($page = 1, $cond = [], $size = 40)
    {
        $where = "";
        foreach ($cond as $key => $val) {
            switch ($key) {
                case "in":
                    $where .= $val;
                    break;
                default:
                    $where .= " AND `$key` = '$val' ";
                    break;
            }
        }
        $limit_start = ($page - 1) * $size;
        $sql = "SELECT urls.id, urls.title, urls.url,IF(urls.icon_sina='', urls.icon, urls.icon_sina) icon, urls.remark FROM urls INNER JOIN url_keywords ON urls.id = url_keywords.url_id INNER JOIN keywords ON url_keywords.key_id = keywords.id WHERE 1=1 $where ORDER BY urls.weight DESC limit ?, ? ";
        $result = $this->Model_common->query($sql, [$limit_start, $size]);
        foreach ($result as &$item) {
            $item['url'] = '/site/index/' . $item['id'] . '.html';
            $item['title'] = EmojiUtil::utfToEmoji($item['title']);
            $item['remark'] = EmojiUtil::utfToEmoji($item['remark']);
        }
        return $result;
    }

    public function get($id)
    {
        $result = $this->Model_keywords->get($id);
        return $result;
    }

    public function getPagination($page = 1, $cond = [], $size = 40)
    {
        $result = $this->Model_keywords->getList(false, $cond, $size, 'count(1) num');
        $num = $result[0]['num'];
        $totalPage = ceil($num / $size);
        return ['totalPage' => $totalPage, 'page' => $page];
    }
}
